 package com.immi.servlet;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import javax.xml.crypto.Data;

import org.apache.naming.java.javaURLContextFactory;

import sun.util.resources.CalendarData;

import com.DB.DBHelper;
import com.immiinfo.model.Mymajor;
import com.immiinfo.model.baseInfo;
import com.immiinfo.model.engCap;
import com.immiinfo.model.others;
import com.immiinfo.model.par_major;
import com.immiinfo.model.tiWorkExper;
import com.immiinfo.model.workExper;

/**
 * Servlet implementation class addEvalutionInfo
 */
@WebServlet("/page/client/addEvalutionInfo")
public class addEvalutionInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public addEvalutionInfo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
        response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		
		//如果用户提交了订单,基本信息
		baseInfo bas=new baseInfo();
		int isMarry=0;
		List<baseInfo> resultInfor=DBHelper.getShowInfo();
		int size=resultInfor.size();
		String tempEmail=new String(request.getParameter("email").getBytes("ISO-8859-1"),"UTF-8");
		for(int k=0;k<size;k++){
			if(tempEmail.equals(resultInfor.get(k).getE_mail()))
			{
				response.getWriter().print("<script language=javascript>alert('该邮箱已经被使用！');"
			      		+ "window.location.href='/immigration/page/client/client_evaluation_test.jsp';</script>");
				//System.out.print("alert("")");
				return ;
			}
		}
		if(request.getParameter("email")!=null)
		{
			String tempCity=new String(request.getParameter("city").getBytes("ISO-8859-1"),"UTF-8");
			bas.setCity(tempCity);
			bas.setE_mail(request.getParameter("email"));
			
			String genderTemp=new String(request.getParameter("gender").getBytes("ISO-8859-1"),"UTF-8");
			bas.setGender(genderTemp);
			String immicounTemp=new String(request.getParameter("immicountry").getBytes("ISO-8859-1"),"UTF-8");
			bas.setImiCountry(immicounTemp);
			String nameTemp=new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");		
			bas.setName(nameTemp);
			bas.setTelNumber(request.getParameter("phonenumber"));
			bas.setDataOfBir(request.getParameter("birthday1"));
			String qqTemp=new String(request.getParameter("QQ").getBytes("ISO-8859-1"),"UTF-8");
			String weixinTemp=new String(request.getParameter("QQ").getBytes("ISO-8859-1"),"UTF-8");
			bas.setqq(qqTemp);
			bas.setweixin(weixinTemp);
			if(request.getParameter("isMarry")!=null)
			{
				isMarry=new Integer(request.getParameter("isMarry"));
			}
			bas.setIsMarry(isMarry);
			if(isMarry==0)
			{
				bas.setPartnerBir("");
			}
			else
			{
				bas.setPartnerBir(request.getParameter("Partnerbirthday"));
			}
		
		//2,英语考试
		String isPass=request.getParameter("passExam");
		//如果通过考试，把考试信息存入数据库中
		engCap engcap=new engCap();
		if(isPass!=null)
		{
			if(isPass.equals("1"))
			{				
				engcap.setE_mail(request.getParameter("email"));
				String englishType=new String(request.getParameter("english_text_type").getBytes("ISO-8859-1"),"UTF-8");
				engcap.setEngType(englishType);
				engcap.setListening(request.getParameter("listening"));
				engcap.setSpeaking(request.getParameter("speaking"));
				engcap.setReading(request.getParameter("reading"));
				engcap.setWriting(request.getParameter("writing"));
				DBHelper.InsertEngCapToDB(engcap);
			}	
		}
		//3，工作经历
		String hasWorExper=request.getParameter("offjob");
		if(hasWorExper!=null)
		{
			if(hasWorExper.equals("1"))
			{
			
			//	System.out.print(WorkExperCount);
				for(int j=0;j<6;j++)
				{
					String name="job"+(j+1);
					if(request.getParameter(name)!=null){
					String jobAttrName="job"+(j+1);
					String tempJob=new String(request.getParameter(jobAttrName).getBytes("ISO-8859-1"),"UTF-8");
					if(tempJob!=null){
					workExper workexper=new workExper();
					workexper.setEmail(request.getParameter("email"));									
					workexper.setJob(tempJob);
					String workstartAttrName="work_starttime"+(j+1);
					workexper.setStartTime(request.getParameter(workstartAttrName));
					String workendAttrName="work_endtime"+(j+1);
					workexper.setEndTime(request.getParameter(workendAttrName));
					String countryAttrName="country"+(j+1);
					String tempCountry=new String(request.getParameter(countryAttrName).getBytes("ISO-8859-1"),"UTF-8");
					workexper.setWork_country(tempCountry);		
				    DBHelper.InsertworkExperToDB(workexper);}}
				}
			}
		}
		String hasTiWorExper=request.getParameter("ishasTiWorkEx");
		tiWorkExper tiWorkEx=new tiWorkExper();
		
				
				tiWorkEx.setEmail(request.getParameter("email"));
				String tempIn_aus_work=new String(request.getParameter("in_aus_work").getBytes("ISO-8859-1"),"UTF-8");
				tiWorkEx.setIn_aus_work(tempIn_aus_work);
				String tempOut_aus_work=new String(request.getParameter("out_aus_work").getBytes("ISO-8859-1"),"UTF-8");
				tiWorkEx.setOut_aus_work(tempOut_aus_work);
				DBHelper.InsertTiWorkExperToDB(tiWorkEx);
				
			
		
		//学历信息
		Mymajor major=new Mymajor();
		if(request.getParameter("eduLevel")!=null)
		{
			String eduLevel=new String(request.getParameter("eduLevel").getBytes("ISO-8859-1"),"UTF-8");
			major.setEduLevel(eduLevel);
			String majortemp=new String(request.getParameter("major1").getBytes("ISO-8859-1"),"UTF-8");
			major.setMajor(majortemp);
		    String country=new String(request.getParameter("majorCountry").getBytes("ISO-8859-1"),"UTF-8");
		    major.setMajorInCountry(country);
	        major.setMaStartTimeString(request.getParameter("begintime1"));
	        major.setMaEndTimeString(request.getParameter("endtime1")); 
	        major.setEmail(request.getParameter("email"));
	        DBHelper.InsertEduLevelToDB(major);
		}
		if(request.getParameter("bachelor")!=null){
			Mymajor bacherlor=new Mymajor();
			String eduLevel=new String(request.getParameter("bachelor").getBytes("ISO-8859-1"),"UTF-8");
			bacherlor.setEduLevel(eduLevel);
			String majortemp=new String(request.getParameter("bachelormajor").getBytes("ISO-8859-1"),"UTF-8");
			bacherlor.setMajor(majortemp);
		    String country=new String(request.getParameter("bachelorcountry").getBytes("ISO-8859-1"),"UTF-8");
		    bacherlor.setMajorInCountry(country);
		    bacherlor.setMaStartTimeString(request.getParameter("bachelorstarttime"));
		    bacherlor.setMaEndTimeString(request.getParameter("bachelorendtime")); 
		    bacherlor.setEmail(request.getParameter("email"));
	        DBHelper.InsertEduLevelToDB(bacherlor);
		}
		//其它
		List<others> otherList=new ArrayList();
		if(request.getParameter("other")!=null)
		{
			String []other=request.getParameterValues("other");
			String emailtemp=request.getParameter("email");
			
			for(int i=0;i<other.length;i++)
			{
				others temp=new others();
				temp.setEmail(emailtemp);
				temp.setOther(new String(other[i].getBytes("ISO-8859-1"),"UTF-8"));
				otherList.add(i, temp);
			}
			DBHelper.InsertOthersToDB(otherList);
		}
		//配偶的相关信息
		String ParthasTiWorExper=request.getParameter("ParishasTiWorkEx");
		int isMarray=0;
		if(request.getParameter("isMarry")!=null)
		{
			isMarray=new Integer(request.getParameter("isMarry"));
		}
		engCap parengcap=new engCap();
		if(isMarray==1)//结婚了
		{
			//2,英语考试
			String isPartnerString=request.getParameter("isPartenrPass");
			
			//如果通过考试，把考试信息存入数据库中
			if(isPartnerString!=null)
			{
				if(isPartnerString.equals("1"))
				{
					
					parengcap.setE_mail(request.getParameter("email"));
					String englishType=new String(request.getParameter("english_text_type2").getBytes("ISO-8859-1"),"UTF-8");
					parengcap.setEngType(englishType);
					parengcap.setListening(request.getParameter("listening2"));
					parengcap.setSpeaking(request.getParameter("speaking2"));
					parengcap.setReading(request.getParameter("reading2"));
					parengcap.setWriting(request.getParameter("writing2"));
					DBHelper.InsertPartnerEngCapToDB(parengcap);
				}				
			}
			//配偶的工作经验
		String patnerHasWorExper=request.getParameter("paroffjob");
	 
	    
		if(patnerHasWorExper!=null)
		{
			if(patnerHasWorExper.equals("1"))
			{
				
				for(int j=0;j<6;j++)
				{
					String name="par_job"+(j+1);
					if(request.getParameter(name)!=null){
					workExper workexper=new workExper();
					workexper.setEmail(request.getParameter("email"));
					String jobAttrName="par_job"+(j+1);
					String tempJob=new String(request.getParameter(jobAttrName).getBytes("ISO-8859-1"),"UTF-8");
					workexper.setJob(tempJob);
					String workstartAttrName="par_work_starttime"+(j+1);
					workexper.setStartTime(request.getParameter(workstartAttrName));
					String workendAttrName="par_work_endtime"+(j+1);
					workexper.setEndTime(request.getParameter(workendAttrName));
					String countryAttrName="par_country"+(j+1);
					String tempCountry=new String(request.getParameter(countryAttrName).getBytes("ISO-8859-1"),"UTF-8");
					workexper.setWork_country(tempCountry);
					DBHelper.InsertPartnerWorkExperToDB(workexper);
				}
				}
			}
		}
		
		
		tiWorkExper partiWorkEx=new tiWorkExper();
		if(ParthasTiWorExper!=null)
		{
				partiWorkEx.setEmail(request.getParameter("email"));
				String tempIn_aus_work1=new String(request.getParameter("par_in_aus_work").getBytes("ISO-8859-1"),"UTF-8");
				partiWorkEx.setIn_aus_work(tempIn_aus_work1);
				String tempOut_aus_work1=new String(request.getParameter("par_out_aus_work").getBytes("ISO-8859-1"),"UTF-8");
				partiWorkEx.setOut_aus_work(tempOut_aus_work1);
				DBHelper.InsertParTiWorkExperToDB(partiWorkEx);

		}
		//配偶的学历
		Mymajor partnermajor=new Mymajor();
		if(request.getParameter("PartnereduLevel")!=null)
		{
			String eduLevel=new String(request.getParameter("PartnereduLevel").getBytes("ISO-8859-1"),"UTF-8");
			partnermajor.setEduLevel(eduLevel);
			String majortemp=new String(request.getParameter("major2").getBytes("ISO-8859-1"),"UTF-8");
			partnermajor.setMajor(majortemp);
		    String country=new String(request.getParameter("majorcountry2").getBytes("ISO-8859-1"),"UTF-8");
		    partnermajor.setMajorInCountry(country);
		    partnermajor.setMaStartTimeString(request.getParameter("begintime2"));
		    partnermajor.setMaEndTimeString(request.getParameter("endtime2")); 
		    partnermajor.setEmail(request.getParameter("email"));
	        DBHelper.InsertParEduLevelToDB(partnermajor);
		}	
		if(request.getParameter("parbachelor1")!=null){
			Mymajor parbacherlor=new Mymajor();
			String eduLevel=new String(request.getParameter("parbachelor1").getBytes("ISO-8859-1"),"UTF-8");
			parbacherlor.setEduLevel(eduLevel);
			String majortemp=new String(request.getParameter("parbachelormajor1").getBytes("ISO-8859-1"),"UTF-8");
			parbacherlor.setMajor(majortemp);
		    String country=new String(request.getParameter("parbachelorcountry1").getBytes("ISO-8859-1"),"UTF-8");
		    parbacherlor.setMajorInCountry(country);
		    parbacherlor.setMaStartTimeString(request.getParameter("parbachelorstarttime1"));
		    parbacherlor.setMaEndTimeString(request.getParameter("parbachelorendtime1")); 
		    parbacherlor.setEmail(request.getParameter("email"));
	        DBHelper.InsertParEduLevelToDB(parbacherlor);
		}
		}
		PrintWriter outPrintWriter=response.getWriter();
		int totalScore=0;
		//英语分
		   String engType=engcap.getEngType();
		int engScore=0;
		if(isPass.equals("1"))
		{
		               // String engType=engcap.getEngType();
	                    if("雅思（IELTS）A".equals(engType)||"雅思（IELTS）G".equals(engType))
			                  { 	
			                	  Double lis=Double.parseDouble(engcap.getListening());
			      			      Double spe=Double.parseDouble(engcap.getSpeaking());
			                      Double read=Double.parseDouble(engcap.getReading());
			    			      Double wri=Double.parseDouble(engcap.getWriting());
			                	  if(lis<7||spe<7||read<7||wri<7)
			                	  {
			                		  engScore=0;
			                	  }
			                	  else {
									if(((lis<8)||(spe<8)||(read<8)||(wri<8))&&lis>=7&&spe>=7&&read>=7&&wri>=7)
									{
										engScore=10;
									}
									if((lis>=8)&&(spe>=8)&&(read>=8)&&(wri>=8))
									{
										engScore=20;
									}
								}
			                  }
	                    if("职业英语考试（OET）".equals(engType))
		                  { 	
		                	  String lis=engcap.getListening();
		      			      String spe=engcap.getSpeaking();
		                      String read=engcap.getReading();
		    			     String wri=engcap.getWriting();
		                	  if("A".equals(lis)&&"A".equals(spe)&&"A".equals(read)&&"A".equals(wri))
		                	  {
		                		  engScore=20;
		                	  }
		                	  else {
								if(("C".equals(lis)||"C".equals(spe)||"C".equals(read)||"C".equals(wri))||("D".equals(lis)||"D".equals(spe)||"D".equals(read)||"D".equals(wri))||("E".equals(lis)||"E".equals(spe)||"E".equals(read)||"E".equals(wri)))
								{
									engScore=0;
								}
								else
								{
									engScore=10;
								}
							}
		                  }
	                    if("托福（TOEFL）".equals(engType))
		                  { 	
		                	  Double lis=Double.parseDouble(engcap.getListening());
		      			      Double spe=Double.parseDouble(engcap.getSpeaking());
		                      Double read=Double.parseDouble(engcap.getReading());
		    			      Double wri=Double.parseDouble(engcap.getWriting());
		                	  if(lis<24||spe<23||read<24||wri<27)
		                	  {
		                		  engScore=0;
		                	  }
		                	  else {
								if(((lis<28)||(spe<26)||(read<29)||(wri<30))&&lis>=24&&spe>=23&&read>=24&&wri>=27)
								{
									engScore=10;
								}
								if((lis>=28)&&(spe>=26)&&(read>=29)&&(wri>=30))
								{
									engScore=20;
								}
							}
		                  }
	                    if("学术英语考试（PTE）".equals(engType))
		                  { 	
		                	  Double lis=Double.parseDouble(engcap.getListening());
		      			      Double spe=Double.parseDouble(engcap.getSpeaking());
		                      Double read=Double.parseDouble(engcap.getReading());
		    			      Double wri=Double.parseDouble(engcap.getWriting());
		                	  if(lis<65||spe<65||read<65||wri<65)
		                	  {
		                		  engScore=0;
		                	  }
		                	  else {
								if(((lis<79)||(spe<79)||(read<79)||(wri<79))&&lis>=65&&spe>=65&&read>=65&&wri>=65)
								{
									engScore=10;
								}
								if((lis>=79)&&(spe>=79)&&(read>=79)&&(wri>=79))
								{
									engScore=20;
								}
							}
		                  }
	                    if("剑轿英语等级证书考试（CAE）".equals(engType))
		                  { 	
		                	  String lis=engcap.getListening();
		      			      String spe=engcap.getSpeaking();
		                      String read=engcap.getReading();
		    			     String wri=engcap.getWriting();
		                	  if(">200".equals(lis)&&">200".equals(spe)&&">200".equals(read)&&">200".equals(wri))
		                	  {
		                		  engScore=20;
		                	  }
		                	  else {
								if("<185".equals(lis)||"<185".equals(spe)||"<185".equals(read)||"<185".equals(wri))
								{
									engScore=0;
								}
								else
								{
									engScore=10;
								}
							}
		                  }             
		}
		totalScore=totalScore+engScore;
		//年龄分
		int ageScore=0;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date bir=new Date();
		try {
			bir = sdf.parse(bas.getDateOfBir());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int birYear=bir.getYear();
		int birMonth=bir.getMonth();
		int birDay=bir.getDay();
		String tempnow=sdf.format(new Date());
		Date now=new Date();
		try {
			now = sdf.parse(tempnow);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int year=now.getYear()-birYear;
		int month=now.getMonth()-birMonth;
		int day=now.getDay()-birDay;

		if((year<18)||(year==18&&month<0)||(year==18&&month==0&&day<0))//未满18周岁
		   {ageScore=0;}
		else
	       if(year>45||(year==45&&month>0)||(year==45&&month==0&&day>=0))//超过45周岁
	          {ageScore=0;}
	       else//18-44
		  {
	    	if((year<25)||(year==25&&month==0&&day<0)||(year==25&&month<0))//18-24
	    	{
	    		ageScore=25;
	    	}
	    	else //25-44
	    	{
				if((year<33)||(year==33&&month==0&&day<0)||(year==33&&month<0))//25-32
				{
					ageScore=30;
				}
				else {
					if((year<40)||(year==40&&month==0&&day<0)||(year==40&&month<0))
					{
						ageScore=25;
					}
					else{
						ageScore=15;
					}
				}
			}
		  }
		int parScore=0;
		if(isMarray==1){
		Date parbir=new Date();
		try {
			parbir = sdf.parse(bas.getPartnerBir());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int parbirYear=parbir.getYear();
		int parbirMonth=parbir.getMonth();
		int parbirDay=parbir.getDay();
		//String tempnow=sdf.format(new Date());
		//Date now=new Date();
	/*	try {
			now = sdf.parse(tempnow);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		int paryear=now.getYear()-parbirYear;
		int parmonth=now.getMonth()-parbirMonth;
		int parday=now.getDay()-parbirDay;
		if(ParthasTiWorExper.equals("1"))
		{
			if(paryear<50||(paryear==50&&parmonth<0)||(paryear==50&&parmonth==0&&parday<0))
			{
				parScore=5;
			}
		}
		
		}
		totalScore+=parScore;
		totalScore+=ageScore;
		//提名职业加分
		int jobScore_in=0;
		int jobScore_out=0;
		if("在澳大利亚已经受雇佣一年".equals(tiWorkEx.getIn_aus_work())){
			jobScore_in=5;
		}
		if("在澳大利亚已经受雇佣三年".equals(tiWorkEx.getIn_aus_work())){
			jobScore_in=10;
		}
		if("在澳大利亚已经受雇佣五年".equals(tiWorkEx.getIn_aus_work())){
			jobScore_in=15;
		}
		if("在澳大利亚已经受雇佣八年".equals(tiWorkEx.getIn_aus_work())){
			jobScore_in=20;
		}
		if("在澳大利亚以外国家已经受雇佣三年".equals(tiWorkEx.getOut_aus_work()))
		{
			jobScore_out=5;
		}
		if("在澳大利亚以外国家已经受雇佣五年".equals(tiWorkEx.getOut_aus_work()))
		{
			jobScore_out=15;
		}
		if("在澳大利亚以外国家已经受雇佣八年".equals(tiWorkEx.getOut_aus_work()))
		{
			jobScore_out=5;
		}
		int skilljobscore=0;
		if(jobScore_in+jobScore_out>20){skilljobscore=20;}
		else{
			skilljobscore=jobScore_in+jobScore_out;
		}
		totalScore+=skilljobscore;
		int quaScore=0;
	
		//学历加分
		if("专科或其他文凭".equals(major.getEduLevel()))
		{
			quaScore=10;
		}
		if("本科学位".equals(major.getEduLevel())||"硕士学位".equals(major.getEduLevel()))
		{
			quaScore=15;
		}
		if("博士学位".equals(major.getEduLevel()))
		{
			quaScore=20;
		}
		//if(jobScore_in+jobScore_out>20){totalScore=totalScore+20;}
		totalScore+=quaScore;
		//其他加分
		totalScore+=otherList.size()*5;		
		bas.setadmitdate(tempnow);
		bas.settotalscore(totalScore);
		DBHelper.InterBaseInfoToDB(bas);
		//outPrintWriter.println("总分是："+totalScore);   
		String showInfo="您的评估总分为"+totalScore+"！\\n年龄分："+ageScore+"\\n英语能力分："+engScore+"\\n提名职业加分："+(skilljobscore)+"\\n学历分："+quaScore+"\\n其它选项分："+otherList.size()*5+"\\n配偶分："+parScore;
		response.getWriter().print("<script language=javascript>alert('"+showInfo+"');"
	      		+ "window.location.href='/immigration/page/client/client_evaluation_test.jsp';</script>");
		/* JOptionPane.showMessageDialog(null, showInfo, "总分", JOptionPane.PLAIN_MESSAGE); 
	    RequestDispatcher dispatcher=request.getRequestDispatcher("/page/client/client_evaluation_test.jsp");
		 dispatcher.forward(request, response);*/
	}
}
}
